package com.lsh.wechat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/9/17 10:45 上午
 * @desc ：
 */
public class WeChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //初始化  构造器
    public WeChatServer(){
        try{
            //得到选择器
            selector = Selector.open();
            //获得ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //将ServerSocketChannel注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try{
            //循环处理
            while(true){
//                int count = selector.select(2000);
                int count = selector.select();
                if (count>0){//有事件要处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //监听accept事件
                        if (key.isAcceptable()){
                            SocketChannel accept = listenChannel.accept();
                            //设置非阻塞
                            accept.configureBlocking(false);
                            //将accept注册到Selector
                            accept.register(selector,SelectionKey.OP_READ);
                            // 上线提示
                            System.out.println(accept.getRemoteAddress()+" 上线了");
                        }
                        if (key.isReadable()){
                            //通道发生 READ事件
                            //从通道中读取数据到BUffer中
                            readData(key);
                        }
                        //当前的key删除，防止重复处理
                        iterator.remove();
                    }
                }else {
                    System.out.println("等待中...");
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void  readData (SelectionKey key)  {
            //定义一个SocketChannel
            //得到关联的channel
            SocketChannel channel= (SocketChannel)key.channel();
            //创建Buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
             int count = channel.read(byteBuffer);
            if (count>0){
                String msg = new String(byteBuffer.array());
                System.out.println("客户端消息： "+msg);
                //向其他客户端转发消息
                sendInfoOther(msg,channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress()+" 离线了...");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void sendInfoOther(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器转发消息");
        //遍历所有注册到selectorng上的SocketorChannel  并排除自己
        for (SelectionKey key : selector.keys()) {
            //通过key 取出对应的SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel!= self){
                SocketChannel dest =  (SocketChannel)targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将buffer中的数据写入到通道中
                dest.write(buffer);
            }
        }
    }
    public static void main(String[] args) {
        WeChatServer weChatServer = new WeChatServer();
        weChatServer.listen();
    }





}
